<template>
  <div class="app-container">
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <template v-for="item in columnConfigs">
          <!--     文本输入框     -->
          <el-input
            v-if="item.qqIsQuery === '1' && ( item.qqQueryType === null || item.qqQueryType === 'INPUT' )"
            :key="item.colName"
            v-model="query[item.colName]"
            size="small"
            style="width: 200px"
            class="filter-item"
            clearable
            :placeholder="`请输入${item.colCname}`"
          />
          <!--     码值字符串     -->
          <el-select
            v-else-if="item.qqIsQuery === '1' && item.qqQueryType === 'SELECT_STRING'"
            :key="item.colName"
            v-model="query[item.colName]"
            size="small"
            style="width: 200px"
            class="filter-item"
            clearable
            placeholder="全部"
          >
            <el-option
              v-for="keyValue in item.qqQueryTypeConf.split(';')"
              :key="keyValue.split(':')[0]"
              :label="keyValue.split(':')[1]"
              :value="keyValue.split(':')[0]"
            />
          </el-select>
          <!--     数据字典     -->
          <el-select
            v-else-if="item.qqIsQuery === '1' && item.qqQueryType === 'SELECT_DICT'"
            :key="item.colName"
            v-model="query[item.colName]"
            size="small"
            style="width: 200px"
            class="filter-item"
            clearable
            placeholder="全部"
          >
            <el-option
              v-for="dictionary in dict[item.qqQueryTypeConf]"
              :key="dictionary.id"
              :label="dictionary.label"
              :value="dictionary.value"
            />
          </el-select>
          <!--   日期    -->
          <el-date-picker
            v-if="item.qqIsQuery === '1' && item.qqQueryType === 'DATE'"
            :key="item.colName"
            v-model="query[item.colName]"
            type="datetime"
            size="small"
            style="width: 200px"
            class="filter-item"
            clearable
            :placeholder="`选择${item.colCname}`"
          />
        </template>
        <rr-operation :crud="crud" />
      </div>
      <crudOperation :permission="permission">
        <el-button
          slot="beforeExport"
          v-permission="['admin']"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :loading="crud.delAllLoading"
          :disabled="crud.selections.length === 0"
          @click="toDelete(crud.selections)"
        >
          删除
        </el-button>
        <el-button
          slot="beforeExport"
          v-permission="['admin']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="dialog = true"
        >
          导入
        </el-button>
        <el-button
          slot="right"
          v-permission="['admin']"
          :loading="crud.downloadLoading"
          :disabled="!crud.data.length"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-download"
          @click="doExport(crud.selections)"
        >导出</el-button>
      </crudOperation>
    </div>
    <!--  新增  -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0 && crud.status.add > 0" :title="crud.status.title" width="600px" top="10px">
      <el-form ref="form" :model="form" size="small" label-width="100px">
        <el-form-item label="表名" prop="componentName" hidden>
          <el-input v-model="form.componentName" />
        </el-form-item>
        <template v-for="item in columnConfigs">
          <el-form-item
            v-if="item.uuCanUpdate === 'A' || item.uuCanUpdate === 'C'"
            :key="item.colName"
            :label="item.colCname"
            :prop="item.colName"
          >
            <el-date-picker
              v-if="item.uuUpdateType === 'DATE'"
              v-model="form[item.colName]"
              type="datetime"
              placeholder="请选择日期时间"
            />
            <el-select v-else-if="item.uuUpdateType === 'SELECT_DICT'" v-model="form[item.colName]">
              <el-option
                v-for="dictionary in dict[item.uuUpdateTypeConf]"
                :key="dictionary.id"
                :label="dictionary.label"
                :value="dictionary.value"
              />
            </el-select>
            <el-input v-else v-model="form[item.colName]" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--  修改  -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0 && crud.status.edit > 0" :title="crud.status.title" width="600px" top="10px">
      <el-form ref="form" :model="form" size="small" label-width="100px">
        <el-form-item label="表名" prop="componentName" hidden>
          <el-input v-model="form.componentName" />
        </el-form-item>
        <template v-for="item in columnConfigs">
          <el-form-item
            v-if="item.uuCanUpdate === 'A' || item.uuCanUpdate === 'U'"
            :key="item.colName"
            :label="item.colCname"
            :prop="item.colName"
          >
            <el-date-picker
              v-if="item.uuUpdateType === 'DATE'"
              v-model="form[item.colName]"
              type="datetime"
              placeholder="请选择日期时间"
            />
            <el-select v-else-if="item.uuUpdateType === 'SELECT_DICT'" v-model="form[item.colName]">
              <el-option
                v-for="dictionary in dict[item.uuUpdateTypeConf]"
                :key="dictionary.id"
                :label="dictionary.label"
                :value="dictionary.value"
              />
            </el-select>
            <el-input v-else v-model="form[item.colName]" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!-- 导入  -->
    <el-dialog :visible.sync="dialog" :close-on-click-modal="false" append-to-body width="600px">
      <el-upload
        drag
        :auto-upload="false"
        :limit="1"
        action=""
        :on-exceed="onExceed"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doImport">确认</el-button>
      </div>
    </el-dialog>
    <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55" />
      <template v-for="item in columnConfigs">
        <el-table-column
          v-if="item.ssIsShow !== 'N' && item.ssIsShow !== 'D'"
          :key="item.colName"
          :label="item.colCname"
          :show-overflow-tooltip="true"
          :prop="item.colName"
        />
      </template>
    </el-table>
    <pagination />
  </div>
</template>

<script>
import crudOperation from '@crud/CRUD.operation'
import rrOperation from '@crud/RR.operation'
import { getColumnsConfig } from '@/api/postRecord/general'
import crudGeneral from '@/api/postRecord/general'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import { getDicts } from '@/api/system/dict'
// import { get as getDictDetail } from '@/api/system/dictDetail'
import Vue from 'vue'

const defaultCrud = CRUD({ url: 'api/general', crudMethod: { ...crudGeneral }})
const defaultForm = {}
export default {
  name: 'CfgList',
  components: {
    crudOperation,
    rrOperation,
    pagination
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    // 存放字典码值
    const dict = {
      dict: {},
      label: {}
    }
    return {
      columnConfigs: [],
      dict,
      dialog: false,
      fileList: [],
      permission: {
        add: ['admin'],
        edit: ['admin'],
        del: ['admin']
      }
    }
  },
  beforeCreate() {
    // 设置CRUD默认标题
    defaultCrud.title = this.$route.meta.title
    // 设置CRUD默认查询参数componentName
    defaultCrud.params.componentName = this.$route.name
    // 设置表单componentName默认值
    defaultForm.componentName = this.$route.name
    // 初始化表单
    getColumnsConfig(this.$route.name).then(resolve => {
      for (const item of resolve) {
        defaultForm[item.colName] = null
      }
    })
    // 页面初始化注入数据前，加载所有码值表数据
    // getDicts().then(data => {
    //   data.forEach(n => {
    //     Vue.set(this.dict.dict, n.name, {})
    //     Vue.set(this.dict.label, n.name, {})
    //     Vue.set(this.dict, n.name, [])
    //     getDictDetail(n.name).then(res => {
    //       this.dict[n.name].splice(0, 0, ...res.content)
    //       res.content.forEach(d => {
    //         Vue.set(this.dict.dict[n.name], d.value, d)
    //         Vue.set(this.dict.label[n.name], d.value, d.label)
    //       })
    //     })
    //   })
    // })
  },
  created() {
    this.crud.optShow = {
      add: true,
      edit: true,
      del: false,
      download: false
    }
    // 获取路由配置中组件的名称作为表名
    const cpnName = this.$route.name
    // 根据表名查询表结构
    this.getColumnsConfig(cpnName)
  },
  methods: {
    getColumnsConfig(cpnName) {
      getColumnsConfig(cpnName).then(resolve => {
        this.columnConfigs = resolve
      })
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(datas, this.$route.name)
      }).catch(() => {
      })
    },
    doDelete(datas, componentName) {
      this.crud.crudMethod.del(datas, componentName).then(() => {
        this.crud.dleChangePage(1)
        this.crud.delSuccessNotify()
        this.crud.refresh()
      })
    },
    doExport() {
      this.crud.doExport()
    },
    doImport() {
      console.log('开始导入')
    },
    onExceed() {
      const h = this.$createElement
      this.$msgbox({
        title: '警告',
        message: h('p', null, [
          h('span', null, '最大只能上传一个文件')
        ]),
        confirmButtonText: '确定'
      })
    }
  }
}
</script>
